---
title: "多线程上使用SecurityContextHolder"
date: 2021-1-25
categories:
- java
- spring-security
tags:
---

<div id="content">
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#org5ddfd2a">在子线程中也能获取到SecurityContext</a></li>
<li><a href="#org0b718da">Executor的执行线程中访问SecurityContext</a></li>
<li><a href="#orgb6053c5">Spring Async</a></li>
</ul>
</div>
</div>
<div class="outline-2" id="outline-container-org5ddfd2a">
<h2 id="org5ddfd2a">在子线程中也能获取到SecurityContext</h2>
<div class="outline-text-2" id="text-org5ddfd2a">
<p>
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL)
</p>
<div class="org-src-container">
<pre class="src src-java">SecurityContextHolder.setStrategyName(<span style="font-weight: bold; text-decoration: underline;">SecurityContextHolder</span>.<span style="font-weight: bold; text-decoration: underline;">MODE_INHERITABLETHREADLOCAL</span>)

<span style="font-weight: bold;">new</span> <span style="font-weight: bold; text-decoration: underline;">Thread</span>(() -&gt; {
        <span style="font-weight: bold; text-decoration: underline;">Authentication</span> <span style="font-weight: bold; font-style: italic;">authentication</span> = SecurityContextHolder.getContext().getAuthentication();

});
</pre>
</div>
</div>
</div>
<div class="outline-2" id="outline-container-org0b718da">
<h2 id="org0b718da">Executor的执行线程中访问SecurityContext</h2>
<div class="outline-text-2" id="text-org0b718da">
<p>
使用Spring Security提供的DelegatingSecurityContextAsyncTaskExecutor实现
</p>
</div>
</div>
<div class="outline-2" id="outline-container-orgb6053c5">
<h2 id="orgb6053c5">Spring Async</h2>
<div class="outline-text-2" id="text-orgb6053c5">
<p>
同上，注册一个DelegatingSecurityContextAsyncTaskExecutor Bean到Spring窗口中，需要正确配置Spring Async使用Executor是那个配置的Bean
</p>
</div>
</div>
</div>
<div class="status" id="postamble">
<p class="date">Date: 2021-1-25</p>
<p class="author">Author: gdme1320</p>
<p class="validation"><a href="http://validator.w3.org/check?uri=referer">Validate</a></p>
</div>
